import React, { Component } from 'react';
import { connect } from 'dva';
import styles from '../index.css';
import sty from './index.css';
import styles1 from '../userManage/index.css';
// import { Dispatch, AnyAction } from 'redux';
import {
  Button,
  Table,
  Select,
  Input,
  Pagination,
  Modal,
  Tree,
  message,
  Spin,
  Icon,
  Switch,
  Divider,
} from 'antd';
// import { DeviceListsItem } from '@/models/connect';
import { router } from 'umi';
import {
  queryRoleList,
  insertRole,
  deleteRole,
  updateRole,
  checkRoleName,
} from '@/services/systemDevice';
import produce, { Draft } from 'immer';
import { isMenuVisible } from './../../../utils/utils';
import { Dispatch, AnyAction } from 'redux';

const { TreeNode } = Tree;
const { Option } = Select;
const { Column } = Table;

interface RoleManageProps {
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
  rolePageNum: string;
}
class roleManage extends Component {
  constructor(props: RoleManageProps) {
    super(props);
    this.state = {
      isShowModel: false, // 打开弹窗
      isShowMenu: false,
      expandedKeys: [], //树形展开的节点key
      expandedMenuKeys: [], //菜单展开的节点key
      autoExpandParent: true, //自动展开父级
      autoExpandMenuParent: true,
      checkedKeys: [], // 选中的节点id
      checkedMenuKeys: [],
      selectedKeys: [], // 点击的节点id
      curRoleId: undefined, // 点击表格某一行的角色Id
      curRoleName: '', // 点击表格某一行的角色名称
      selcTree: [], // 树形数据
      menuTree: [], //菜单数据
      pageTotal: '', // 列表总数
      isRoleModal: false,
      delectShowModel: false,
      remove: {
        roleIds: '',
      },
      roleModalTitle: '',
      tableData: [], // 表格数据
      roleId: '', // 搜索框的角色id
      roleName: '', // 搜索框的角色名称
      pageNum: 1, // 当前页
      pageSize: 10, // 每页展示数据的条数
      roleDevicePowerList: [], // 选中节点的数据
      menuIds: [],
      bxMenuId: [],
      isPatching: false, // 是否正在加载中
      parameters: {
        //查询条件
        roleId: '', //角色id
        roleName: '', //角色名称
        status: '', //角色状态:0正常,1禁用
        roleSort: '', //显示顺序
        roleKey: '', //角色权限字符串
        dataScope: '', //数据范围（1：所有数据权限；2：自定数据权限）
        pageNum: 1, //页码
        pageSize: 10, //每页显示条数
      },
      parameters1: {
        //新增条件
        roleId: '', //角色id
        userIds: '',
        roleName: '',
        roleKey: '', //角色权限字符串
        roleSort: '', //显示顺序
        dataScope: '1',
        status: '0', //角色状态 0 正常,1禁用
        remark: '',
      },
      isupdate: false,
      actionData: {},
      treePageSize: 10,
      fetchLoading: false,
    };
  }

  // // 角色状态筛选
  // handleChange(val: any) {
  //   console.log(val);
  //   this.setState(
  //     produce((draft: Draft): void => {
  //       draft.parameters.status = val;
  //     }),
  //   );
  // }
  //改变页码数
  onPageChange = (pageNo: Number) => {
    localStorage.setItem('rolePageNum', pageNo);
    this.setState(
      produce((draft: Draft): void => {
        draft.parameters.pageNum = pageNo;
      }),
    );
    isMenuVisible('system:role:list') && this.handleLoading();
    // const { dispatch } = this.props;
    // dispatch({
    //   type: 'systemDevice/applyDeviceLists',
    //   payload: {
    //     roleId: this.state.roleId,
    //     roleName: this.state.roleName,
    //     pageNum: pageNo,
    //     pageSize: 10,
    //   },
    // }).then(() => {
    //   const { systemDevice } = this.props;
    //   this.setState({ tableData: systemDevice.rows, pageTotal: systemDevice.total });
    // });
  };
  // 点击搜索按钮 查询数据
  searchHandle() {
    const { dispatch } = this.props;
    dispatch({
      type: 'systemDevice/applyDeviceLists',
      payload: {
        roleId: this.state.roleId,
        roleName: this.state.roleName,
        pageNum: this.state.pageNum,
        pageSize: 10,
      },
    }).then(() => {
      const { systemDevice } = this.props;
      this.setState({ tableData: systemDevice.rows, pageTotal: systemDevice.total });
    });
  }
  // 监听展开
  onExpand = (expandedKeys: Array<string>) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };
  onMenuExpand = (expandedMenuKeys: Array<string>) => {
    this.setState({
      expandedMenuKeys,
      autoExpandMenuParent: false,
    });
  };

  // 监听选中
  onCheck = (checkedKeys: Array<string>, e: any) => {
    let roleDevicePowerList = [];
    e.checkedNodes.forEach((item: any, idx: number) => {
      if (!!item.props.dataRef.deviceId) {
        roleDevicePowerList.push({
          deviceId: item.props.dataRef.deviceId,
          roleDevicePowerId: item.props.dataRef.roleDevicePowerId,
        });
      }
    });
    this.setState({ checkedKeys, roleDevicePowerList });
  };
  onMenuCheck = (checkedMenuKeys: Array<string>, e: any) => {
    const cm_Keys = checkedMenuKeys.map((e: any) => e);
    const cm_halfKeys = e.halfCheckedKeys && e.halfCheckedKeys.map((e: any) => e);
    this.setState({ checkedMenuKeys: cm_Keys, menuIds: cm_Keys, bxMenuId: cm_halfKeys });
  };
  // 点击节点加载数据
  onLoadData = treeNode =>
    new Promise(resolve => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      setTimeout(() => {
        treeNode.props.dataRef.children = [
          { title: 'Child Node', key: `${treeNode.props.eventKey}-0` },
          { title: 'Child Node', key: `${treeNode.props.eventKey}-1` },
        ];
        this.setState({
          treeData: [...this.state.treeData],
        });
        resolve();
      }, 1000);
    });
  // 渲染树形数据
  renderTreeNodes = (data: Array<any>) =>
    data.map(item => {
      if (!!item.deviceTypeParentNo && item.list) {
        return (
          <TreeNode
            title={item.stuts < 1 ? item.deviceTypeName : item.typeName}
            key={item.stuts < 1 ? item.deviceTypeParentNo : item.deviceTypeNo}
            dataRef={item}
          >
            {this.renderTreeNodes(item.list)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          key={item.stuts < 1 ? item.deviceTypeParentNo : item.deviceTypeNo}
          title={item.stuts < 1 ? item.deviceTypeName : item.typeName}
          dataRef={item}
          {...item}
          loadData={this.onLoadData}
        />
      );
    });
  // 渲染菜单树形数据
  renderMenuTreeNodes = (data: Array<any>) =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.menuName} key={item.menuId} dataRef={item}>
            {this.renderMenuTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.menuName} title={item.menuId} dataRef={item} {...item} />;
    });

  //获取选中的节点
  getCheckedKeys(tree: Array<any>, check_keys: any[]) {
    tree.forEach((e: any) => {
      if (e.stuts && e.stuts === '1') {
        check_keys.push(e.deviceId);
      } else {
        if (e.list && e.list.length) {
          this.getCheckedKeys(e.list, check_keys);
        }
      }
    });
  }
  // 请求后台树形数据
  getTreeData(_record: any) {
    const { dispatch } = this.props;
    this.setState({ isPatching: true });
    dispatch({
      type: 'systemDevice/applyDeviceTreeData',
      payload: { roleId: _record.roleId, parentId: '0' },
    }).then(() => {
      let treeData: any = [];
      const tree = JSON.parse(JSON.stringify(this.props.treeData)); // 请求到的数据
      tree.forEach((e: any) => {
        //将请求到的数据 去除掉 为 null的节点
        if (e.deviceTypeParentNo !== null) {
          treeData.push(e);
        }
      });
      let check_keys: any = [];
      this.getCheckedKeys(tree, check_keys);
      this.setState({
        checkedKeys: check_keys,
        selcTree: treeData,
        isShowModel: true,
        curRoleId: _record.roleId,
        curRoleName: _record.roleName,
        isPatching: false,
      });
    });
  }
  deleteRole = async (_record: any) => {
    this.setState(
      produce((draft: Draft): void => {
        draft.remove.roleIds = _record.roleId;
        draft.delectShowModel = true;
      }),
    );
  };
  handledelete = async () => {
    let res = await deleteRole(this.state.remove);
    message.info(res[2]);
    this.setState(
      produce((draft: Draft): void => {
        draft.remove.roleIds = '';
        draft.delectShowModel = false;
      }),
      () => {
        isMenuVisible('system:role:list') && this.handleLoading();
      },
    );
  };
  updateRole(_record: any) {
    let data = _record;
    this.setState(
      {
        isRoleModal: true,
        roleModalTitle: '修改角色',
        isupdate: true,
        parameters1: data,
        actionData: data,
      },
      () => {},
    );
  }
  addDevicePower() {
    if (this.state.roleDevicePowerList.length) {
      const { dispatch } = this.props;
      this.setState({ fetchLoading: true });
      dispatch({
        type: 'systemDevice/postAddDevice',
        payload: {
          roleDeviceIdList: this.state.roleDevicePowerList,
          sreRoleId: this.state.curRoleId,
        },
      }).then(() => {
        message.success('操作成功');
        this.setState({ isShowModel: false, fetchLoading: false, checkedKeys: [] });
      });
    } else {
      message.warning('请选择设备');
      return;
    }
  }
  addMenuPower() {
    const { dispatch } = this.props;
    this.setState({ fetchLoading: true });
    console.log(this.state);
    dispatch({
      type: 'systemDevice/postAddMenu',
      payload: {
        menuIds: this.state.menuIds.toString(),
        roleId: this.state.curRoleId,
        bxMenuId: this.state.bxMenuId ? this.state.bxMenuId.toString() : this.state.bxMenuId
      },
    }).then(() => {
      message.success('操作成功');
      this.setState({ isShowMenu: false, fetchLoading: false });
      dispatch({
        type: 'systemDevice/menuListBySystemId',
        payload: {
          systemId: localStorage.getItem('surSystemId'),
        },
      });
    });
  }
  handleLoading = async () => {
    const rolePageNum1 = localStorage.getItem('rolePageNum');
    if (rolePageNum1 != null && rolePageNum1 != null) {
      this.setState(
        produce((draft: Draft): void => {
          draft.parameters.pageNum = rolePageNum1;
          draft.pageNum = rolePageNum1;
        }),
        async () => {
          let [err, data] = await queryRoleList(this.state.parameters);
          if (!err) {
            this.setState({
              tableData: data.rows,
              pageTotal: data.total,
            });
          }
        },
      );
    } else {
      let [err, data] = await queryRoleList(this.state.parameters);
      if (!err) {
        this.setState({
          tableData: data.rows,
          pageTotal: data.total,
        });
      }
    }
  };
  onSwitchChange(checked: any) {
    if (checked) {
      this.setState(
        produce((draft: Draft): void => {
          draft.parameters1.status = 0;
        }),
        () => {},
      );
    } else {
      this.setState(
        produce((draft: Draft): void => {
          draft.parameters1.status = 1;
        }),
        () => {},
      );
    }
  }
  addRole = async () => {
    let roleId = this.state.parameters1.roleId;
    let roleName = this.state.parameters1.roleName;
    let roleKey = this.state.parameters1.roleKey;
    let roleSort = this.state.parameters1.roleSort;
    let status = this.state.parameters1.status;
    let remark = this.state.parameters1.remark;
    if (roleName == null || roleName == undefined || roleName == '') {
      message.error('请填写角色名称');
    } else if (roleKey == null || roleKey == undefined || roleKey == '') {
      message.error('请填写角色权限字符');
    } else if (roleSort == null || roleSort == undefined || roleSort == '') {
      message.error('请填写显示顺序');
    } else {
      let roleId = this.state.parameters1.roleId; //角色id
      let roleName = this.state.parameters1.roleName; //角色id
      // roleName: string; //角色名称
      let param1 = { roleId, roleName };
      let res = await checkRoleName(param1);
      if (res[0]) {
      } else {
        if (this.state.isupdate) {
          let param = { roleId, roleName, roleKey, roleSort, status, remark };
          let res = await updateRole(param);
          message.info(res[2]);
          this.setState(
            {
              parameters1: {
                roleId: '', //角色id
                userIds: '',
                roleName: '',
                roleKey: '', //角色权限字符串
                roleSort: '', //显示顺序
                dataScope: '1',
                status: '', //角色状态 0 正常,1禁用
                remark: '',
              },
            },
            () => {},
          );
        } else {
          let res = await insertRole(this.state.parameters1);
          message.info(res[2]);

          this.setState(
            {
              parameters1: {
                roleId: '', //角色id
                userIds: '',
                roleName: '',
                roleKey: '', //角色权限字符串
                roleSort: '', //显示顺序
                dataScope: '1',
                status: '', //角色状态 0 正常,1禁用
                remark: '',
              },
            },
            () => {},
          );
        }
        this.setState({ isRoleModal: false });
        isMenuVisible('system:role:list') && this.handleLoading();
      }
    }
  };
  menuPower = _record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'systemDevice/listBySystemId',
      payload: {
        systemId: localStorage.getItem('surSystemId'),
      },
    }).then(() => {
      const { menuTreeData } = this.props;
      dispatch({
        type: 'systemDevice/queryByRoleInfo',
        payload: {
          roleId: _record.roleId,
        },
      }).then(() => {
        const { selectMenuOpts } = this.props;
        const checkedMenuKeys =
          selectMenuOpts && selectMenuOpts.sysRoleMenus.map((e: any) => e.menuId);
        const halfCheckedKeys =
          selectMenuOpts.sysRoleMenus &&
          selectMenuOpts.sysRoleMenus.length > 0 && selectMenuOpts.sysRoleMenus[0].bxMenuId &&
          selectMenuOpts.sysRoleMenus[0].bxMenuId.split(',');
        this.setState({
          checkedMenuKeys,
          menuIds: checkedMenuKeys,
          bxMenuId: halfCheckedKeys,
          menuTree: menuTreeData,
          isShowMenu: true,
          curRoleId: _record.roleId,
        });
      });
      // this.setState({ menuTree: menuTreeData, isShowMenu: true, curRoleId:_record.roleId })
    });
  };
  componentWillMount() {
    isMenuVisible('system:role:list') && this.handleLoading();
  }
  componentWillReceiveProps(next: any) {
    if (next.isUpdate !== this.props.isUpdate) {
      isMenuVisible('system:role:list') && this.handleLoading();
    }
  }
  columns: any = [
    {
      title: '物品编号',
      dataIndex: 'goodsNo',
      key: 'goodsNo',
    },
    {
      title: '物品名称',
      dataIndex: 'goodsName',
      key: 'goodsName',
    },
    {
      title: '物品种类',
      dataIndex: 'goodsType',
      key: 'goodsType',
    },
    {
      title: '所在位置',
      dataIndex: 'position',
      key: 'position',
    },
    {
      title: '物品状态',
      dataIndex: 'goodsState',
      key: 'goodsState',
    },
    {
      title: '采集时间',
      dataIndex: 'collectTime',
      key: 'collectTime',
    },
  ];
  render() {
    return (
      <Spin
        indicator={<Icon type="loading" style={{ fontSize: 24 }} spin={true} />}
        spinning={this.state.isPatching}
      >
        <div className={styles['role_container']}>
          {isMenuVisible('system:role:add') && (
            <div className={sty.btnAction}>
              <Button
                type="link"
                onClick={() => {
                  this.setState(
                    {
                      isRoleModal: true,
                      roleModalTitle: '新增角色',
                      isupdate: false,
                      parameters1: {
                        roleId: null, //角色id
                        userIds: '',
                        roleName: '',
                        roleKey: '', //角色权限字符串
                        roleSort: null, //显示顺序
                        dataScope: '1',
                        status: '0', //角色状态 0 正常,1禁用
                        remark: '',
                      },
                    },
                    () => {},
                  );
                }}
              >
                <Icon type="plus" />
                新增
              </Button>
            </div>
          )}
          <div style={{ clear: 'both' }}>
            <div className={styles['dev-search']}>
              <div className={styles['dev-search-select']}>
                <Input
                  addonBefore="角色编号"
                  type="text"
                  value={this.state.parameters.roleId}
                  onChange={(e: any) => {
                    const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
                    let datachange = e.target.value.replace(/[, ]/g, '');
                    if (
                      (!isNaN(datachange) && reg.test(datachange)) ||
                      datachange === '' ||
                      datachange === '-'
                    ) {
                      this.setState(
                        produce((draft: Draft): void => {
                          draft.parameters.roleId = datachange;
                          // draft.value = datachange;
                        }),
                      );
                    } else {
                      this.setState(
                        produce((draft: Draft): void => {
                          draft.parameters.roleId = '';
                          // draft.value = '';
                        }),
                        () => {
                          message.error('请填写数字');
                        },
                      );
                    }
                  }}
                />
              </div>
              <div className={styles['dev-search-select']}>
                <Input
                  addonBefore="角色名称"
                  type="text"
                  value={this.state.parameters.roleName}
                  onChange={e => {
                    let datachange = e.target.value;
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.parameters.roleName = datachange;
                      }),
                    );
                  }}
                />
              </div>
              <div className={styles['dev-search-select']}>
                <span className={styles['dev-search-select-title']}>角色状态</span>
                <Select
                  defaultValue="所有"
                  value={this.state.parameters.status}
                  onChange={val => {
                    let datachange = val;
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.parameters.status = datachange;
                      }),
                    );
                  }}
                >
                  <Option value="">所有</Option>
                  <Option value="0">正常</Option>
                  <Option value="1">禁用</Option>
                </Select>
              </div>
              {isMenuVisible('system:role:list') && (
                <Button
                  className={sty.search}
                  size="large"
                  onClick={() => {
                    localStorage.setItem('rolePageNum', '1');
                    const { dispatch } = this.props;
                    dispatch({
                      type: 'systemDevice/setRolePageNum',
                      payload: 1,
                    });
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.parameters.pageNum = 1;
                        draft.pageNum = 1;
                      }),
                      () => {
                        this.handleLoading();
                      },
                    );
                  }}
                >
                  搜索
                </Button>
              )}

              <Button
                className={sty.search}
                size="large"
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.parameters.roleId = '';
                      draft.parameters.roleName = '';
                      draft.parameters.status = '';
                    }),
                    () => {},
                  );
                }}
              >
                重置
              </Button>
            </div>
          </div>

          <div className="tableArea">
            <Table dataSource={this.state.tableData} pagination={false} rowKey="roleId">
              <Column title="角色编号" align="center" dataIndex="roleId" key="roleId" />
              <Column title="角色名称" align="center" dataIndex="roleName" key="roleName" />
              <Column title="权限字符" align="center" dataIndex="roleKey" key="roleKey" />
              <Column title="显示顺序" align="center" dataIndex="roleSort" key="roleSort" />
              <Column
                title="角色状态"
                align="center"
                dataIndex="status"
                key="status"
                render={
                  (_text: number, _record: any) => {
                    return _record.status == 0 ? (
                      <span style={{ color: 'rgb(69, 235, 167)' }}>正常</span>
                    ) : (
                      <span style={{ color: '#cb3203' }}>禁用</span>
                    );
                  }
                  // {_record.status == 0 ?  }
                }
              />
              <Column title="创建时间" align="center" dataIndex="createTime" key="createTime" />
              <Column
                title="操作"
                align="center"
                key="action"
                render={(_text: number, _record: any) => (
                  <span>
                    {isMenuVisible('system:role:update') && (
                      <a
                        onClick={() => {
                          this.updateRole(_record);
                        }}
                        style={{ color: 'rgb(69, 235, 167)' }}
                      >
                        编辑
                      </a>
                    )}
                    {isMenuVisible('system:userRole:list') && (
                      <a
                        onClick={() => {
                          localStorage.setItem('rolePageNum', this.state.pageNum);
                          const { dispatch } = this.props;
                          dispatch({
                            type: 'systemDevice/setRolePageNum',
                            payload: this.state.pageNum,
                          });

                          router.push(`/system/distributionUser/${_record.roleId}`);
                        }}
                      >
                        分配用户
                      </a>
                    )}

                    {isMenuVisible('system:roleDevicePower:select') && (
                      <a
                        onClick={() => {
                          localStorage.setItem('rolePageNum', this.state.pageNum);
                          router.push(`/system/dataPower/${_record.roleId}`);
                        }}
                      >
                        设备权限
                      </a>
                    )}
                    {isMenuVisible('system:roleMenu:inertRoleMenu') && (
                      <a
                        onClick={() => {
                          const { dispatch } = this.props;
                          dispatch({
                            type: 'systemDevice/setRolePageNum',
                            payload: this.state.pageNum,
                          });
                          localStorage.setItem('rolePageNum', this.state.pageNum);
                          this.menuPower(_record);
                        }}
                      >
                        菜单权限
                      </a>
                    )}
                    {isMenuVisible('system:role:remove') && (
                      <a
                        onClick={() => {
                          this.deleteRole(_record);
                        }}
                        style={{ color: '#cb3203' }}
                      >
                        删除
                      </a>
                    )}
                  </span>
                )}
              />
            </Table>
          </div>
          <div className={sty.pageArea}>
            <Pagination
              className={styles.pageHandle}
              showQuickJumper={false}
              // defaultCurrent={this.state.pageNum}
              pageSize={10}
              current={Number(this.state.pageNum)}
              total={this.state.pageTotal}
              onChange={pageNo => {
                let datachange = pageNo;
                localStorage.setItem('rolePageNum', datachange);
                // const { dispatch } = this.props;
                // dispatch({
                //   type: 'systemDevice/setRolePageNum',
                //   payload: datachange,
                // });
                this.setState(
                  produce((draft: Draft): void => {
                    draft.parameters.pageNum = datachange;
                    draft.pageNum = datachange;
                  }),
                  () => {
                    isMenuVisible('system:role:list') && this.handleLoading();
                  },
                );
              }}
            />
            <span className="pagination-title-box">
              第{this.state.pageNum}/
              {Math.ceil(
                (this.state.pageTotal != null ? this.state.pageTotal : 0) / this.state.pageSize,
              )}
              页 共{this.state.pageTotal}条
            </span>
          </div>
        </div>
        <Modal
          title="系统提示"
          visible={this.state.delectShowModel}
          className="delete_role_box"
          onCancel={() => {
            // this.setState({ delectShowModel: false ,remove});
            this.setState(
              produce((draft: Draft): void => {
                draft.remove.roleIds = '';
                draft.delectShowModel = false;
              }),
            );
          }}
          footer={null}
        >
          <div className="delete_titlep">
            <p className="titlep">确定要删除选中数据吗？</p>
          </div>
          <div className={sty.footBtnArea}>
            <div
              className={sty.foot_delete_btn}
              onClick={() => {
                this.handledelete();
              }}
            >
              确定
            </div>
            <div
              className={sty.foot_delete_btn}
              onClick={() => {
                this.setState(
                  produce((draft: Draft): void => {
                    draft.remove.roleIds = '';
                    draft.delectShowModel = false;
                  }),
                );
              }}
            >
              取消
            </div>
          </div>
        </Modal>
        <Modal
          visible={this.state.isRoleModal}
          title={this.state.roleModalTitle}
          centered={true}
          // onOk={this.handleOk}
          className="role_box"
          onCancel={() => {
            this.setState({
              isRoleModal: false,
              parameters: {
                roleId: '', //角色id
                roleName: '', //角色名称
                status: '', //角色状态:0正常,1禁用
                roleSort: '', //显示顺序
                roleKey: '', //角色权限字符串
                dataScope: '', //数据范围（1：所有数据权限；2：自定数据权限）
                pageNum: 1, //页码
                pageSize: 10, //每页显示条数
              },
              parameters1: {
                roleId: '', //角色id
                userIds: '',
                roleName: '',
                roleKey: '', //角色权限字符串
                roleSort: '', //显示顺序
                dataScope: '1',
                status: '0', //角色状态 0 正常,1禁用
                remark: '',
              },
            });
          }}
          footer={null}
        >
          <div className={sty.action_div}>
            <span className={sty.action_span}>角色名称：</span>
            <div className={sty.action_input}>
              <input
                value={this.state.parameters1.roleName}
                onChange={val => {
                  let datachange = val.target.value;
                  if (datachange.length >= 20) {
                    message.error('最多输入20字符');
                  }
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.parameters1.roleName = datachange;
                    }),
                  );
                }}
                maxlength="20"
              />
            </div>
          </div>
          <div className={sty.action_div}>
            <span className={sty.action_span}>权限字符：</span>
            <div className={sty.action_input}>
              <input
                value={this.state.parameters1.roleKey}
                onChange={val => {
                  let datachange = val.target.value;
                  if (datachange.length >= 30) {
                    message.error('最多输入30字符');
                  }
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.parameters1.roleKey = datachange;
                    }),
                  );
                }}
                maxlength="30"
              />
            </div>
          </div>
          <div className={sty.action_div}>
            <span className={sty.action_span}>显示顺序：</span>
            <div className={sty.action_input}>
              <input
                value={this.state.parameters1.roleSort}
                onChange={e => {
                  const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
                  if (
                    (!isNaN(e.target.value) && reg.test(e.target.value)) ||
                    e.target.value === '' ||
                    e.target.value === '-'
                  ) {
                    let datachange = e.target.value;
                    if (datachange.length >= 10) {
                      message.error('最多输入10字符');
                    }
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.parameters1.roleSort = datachange;
                        // draft.value = datachange;
                      }),
                    );
                  } else {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.parameters1.roleSort = '';
                        // draft.value = '';
                      }),
                      () => {
                        message.error('请填写数字');
                      },
                    );
                  }
                }}
                maxlength="10"
              />
            </div>
          </div>
          <div className={sty.action_div}>
            <span className={sty.action_span}>状态：</span>
            <div className={sty.action_input}>
              <Switch
                defaultChecked={this.state.parameters1.status == 0 ? true : false}
                checked={this.state.parameters1.status == 0 ? true : false}
                onChange={e => {
                  this.onSwitchChange(e);
                }}
              />
            </div>
          </div>
          <div className={sty.action_div}>
            <span className={sty.action_span}>备注：</span>
            <div className={sty.action_input}>
              <input
                value={this.state.parameters1.remark}
                onChange={val => {
                  let datachange = val.target.value;
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.parameters1.remark = datachange;
                    }),
                  );
                }}
              />
            </div>
          </div>
          <div className={sty.btnContainer}>
            <div style={{ textAlign: 'center', height: 50, width: 300, margin: '0 auto' }}>
              <div
                style={{ width: 180, height: 40, float: 'none' }}
                className={sty.foot_btn}
                onClick={this.addRole}
                type="primary"
              >
                确定
              </div>
              <div
                style={{ width: 180, height: 40, float: 'none' }}
                className={sty.foot_btn}
                onClick={() => {
                  this.setState({
                    isRoleModal: false,
                    parameters: {
                      roleId: '', //角色id
                      roleName: '', //角色名称
                      status: '', //角色状态:0正常,1禁用
                      roleSort: '', //显示顺序
                      roleKey: '', //角色权限字符串
                      dataScope: '', //数据范围（1：所有数据权限；2：自定数据权限）
                      pageNum: 1, //页码
                      pageSize: 10, //每页显示条数
                    },
                    parameters1: {
                      roleId: '', //角色id
                      userIds: '',
                      roleName: '',
                      roleKey: '', //角色权限字符串
                      roleSort: '', //显示顺序
                      dataScope: '1',
                      status: '0', //角色状态 0 正常,1禁用
                      remark: '',
                    },
                  });
                }}
                type="primary"
              >
                取消
              </div>
            </div>
          </div>
        </Modal>
        <Modal
          visible={this.state.isShowModel}
          title="分配设备数据权限"
          centered={true}
          // onOk={this.handleOk}
          className="device_box"
          onCancel={() => {
            this.setState({ isShowModel: false });
          }}
          footer={null}
        >
          <div>
            <span className={styles.mr50}>角色编号：{this.state.curRoleId}</span>
            <span>角色名称：{this.state.curRoleName}</span>
          </div>
          <div>
            <p>设备数据权限：</p>
            <Tree
              checkable={true}
              // checkStrictly
              onExpand={this.onExpand}
              expandedKeys={this.state.expandedKeys}
              autoExpandParent={this.state.autoExpandParent}
              onCheck={this.onCheck}
              checkedKeys={this.state.checkedKeys}
              // onSelect={this.onSelect}
              // selectedKeys={this.state.selectedKeys}
            >
              {this.renderTreeNodes(this.state.selcTree)}
            </Tree>
            <div className={styles.btnArea}>
              <Button
                style={{ width: 180, height: 40, float: 'none' }}
                onClick={() => {
                  this.addDevicePower();
                }}
                loading={this.state.fetchLoading}
                type="primary"
              >
                确定
              </Button>
              <Button
                style={{ width: 180, height: 40, float: 'none' }}
                onClick={() => {
                  this.setState({ isShowModel: false });
                }}
                type="primary"
              >
                取消
              </Button>
            </div>
          </div>
        </Modal>
        <Modal
          visible={this.state.isShowMenu}
          title="菜单权限"
          centered={true}
          // onOk={this.handleOk}
          className="device_box"
          onCancel={() => {
            this.setState({ isShowMenu: false });
          }}
          footer={null}
        >
          <div>
            <p>菜单权限：</p>
            <Tree
              checkable={true}
              onExpand={this.onMenuExpand}
              expandedKeys={this.state.expandedMenuKeys}
              autoExpandParent={this.state.autoExpandMenuParent}
              onCheck={this.onMenuCheck}
              checkedKeys={this.state.checkedMenuKeys}
            >
              {this.renderMenuTreeNodes(this.state.menuTree)}
            </Tree>
            <div className={styles.btnArea}>
              <Button
                style={{ width: 180, height: 40, float: 'none' }}
                onClick={() => {
                  this.addMenuPower();
                }}
                loading={this.state.fetchLoading}
                type="primary"
              >
                确定
              </Button>
              <Button
                style={{ width: 180, height: 40, float: 'none' }}
                onClick={() => {
                  this.setState({ isShowMenu: false });
                }}
                type="primary"
              >
                取消
              </Button>
            </div>
          </div>
        </Modal>
      </Spin>
    );
  }
}
export default connect(({ loading, systemDevice }: any) => ({
  loading: loading.effects['systemDevice/applyDeviceTreeData'],
  systemDevice: systemDevice.applyDeviceLists,
  treeData: systemDevice.applyDeviceTreeData,
  menuTreeData: systemDevice.listBySystemId,
  selectMenuOpts: systemDevice.queryByRoleInfo,
  rolePageNum: systemDevice.rolePageNum,
}))(roleManage);
